<template>
  <!--产品编辑-->
  <div class="product-edit">
    <div class="product-edit-content">
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-width="auto"
        style="max-width: 600px"
        :rules="rules"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="产品简称" prop="abbreviation">
          <el-input v-model="form.abbreviation" />
        </el-form-item>
        <el-form-item label="所属机构" v-if="editOrAdd" prop="orgId">
          <el-select
            v-model="form.orgId"
            placeholder="请选择机构"
            style="width: 240px"
          >
            <el-option
              v-for="item in orgList"
              :key="item.id"
              :label="item.orgName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构" v-if="!editOrAdd" prop="orgId">
          <el-select
            v-model="form.orgId"
            placeholder="请选择机构"
            style="width: 240px"
            disabled
          >
            <el-option
              v-for="item in orgList"
              :key="item.id"
              :label="item.orgName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品状态">
          <el-switch v-model="form.state" />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select
            v-model="form.businessType"
            placeholder="请选择业务类型"
            style="width: 240px"
          >
            <el-option :value="5" label="以租代购" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            color="rgb(222, 41, 16)"
            type="primary"
            @click="submitForm(ruleFormRef)"
            >保存</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router"; // 引入productouter函数
import http from "@/request/request";
const router = useRouter(); // 获取路由实例
const route = useRoute();
//-----------------------------------------参数定义------------------------//
interface ProductForm {
  id?: number;
  name: string;
  abbreviation: string;
  state: boolean;
  businessType: number;
  orgId?: number;
}
// form表单
const form = ref<ProductForm>({
  name: "",
  abbreviation: "",
  state: true,
  businessType: 5,
});
interface Org {
  id: number;
  orgName: string;
}
const editOrAdd = ref(true);
// 机构列表
const orgList = ref<Org[]>([]);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<ProductForm>>({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  abbreviation: [{ required: true, message: "请输入简称" }],
  orgId: [{ required: true, message: "请选择机构" }],
});

//-----------------------------------------方法定义------------------------//
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (editOrAdd.value) {
        addProduct();
      } else {
        updateProduct();
      }
      router.push("/product");
    } else {
      console.log("error submit!", fields);
      router.back();
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.back();
};
// 查询机构列表
const getAllOrgList = async () => {
  try {
    const { data } = await http.get<Org[]>(
      "/api/system/getEnabledOrgList",
      form
    );
    orgList.value = data;
  } catch (err) {
    console.log(err);
  }
};
// 创建产品
const addProduct = async () => {
  try {
    await http.post<Org[]>("/api/system/createProduct", form.value);
  } catch (err) {
    console.log(err);
  }
};
// 修改产品
const updateProduct = async () => {
  try {
    await http.post<Org[]>("/api/system/updateProduct", form.value);
  } catch (err) {
    console.log(err);
  }
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getProductInfo = async (id: any) => {
  try {
    const { data } = await http.get<ProductForm>(
      "/api/system/getProductDetail",
      { productId: id }
    );
    form.value = data;
  } catch (err) {
    console.log(err);
  }
};
//-----------------------------生命周期-------------------------------//
onMounted(() => {
  getAllOrgList();
  const id = route.query.id;
  // 判断是否有参数传递，如果有参数传递，则进行请求接口，视为修改，否则视为添加
  if (id) {
    console.log("修改");
    editOrAdd.value = false;
    getProductInfo(id);
  } else {
    console.log("添加");
  }
});
</script>

<style lang="less" scoped>
.product-edit {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  background-color: rgb(255, 255, 255);
  .product-edit-content {
    width: 60%;
    padding: 20px;
    padding-top: 50px;
  }
}
</style>